package controllers

import (
	"ErgoGo/internal/model/article"
	"ErgoGo/internal/model/conf"
	articlegenerate "ErgoGo/internal/pkg/articleGenerate"
	"ErgoGo/pkg/http/response"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func GenerateForm(c *gin.Context) {
	// 获取栏目列表
	categories := conf.GetCategories()

	c.HTML(200, "generate", gin.H{
		"title":      "生成文章",
		"showHeader": true,
		"active":     "generate",
		"categories": categories,
	})
}

type GenerateResult struct {
	Success        bool     `json:"success"`
	SuccessCount   int      `json:"success_count"`
	FailedCount    int      `json:"failed_count"`
	FailedKeywords []string `json:"failed_keywords"`
}

func GenerateArticle(c *gin.Context) {
	keywords := c.PostForm("keywords")
	count, _ := strconv.Atoi(c.PostForm("count"))
	isPublish := c.PostForm("publish") == "true"
	tagIds := c.PostForm("tag_ids")
	category := c.PostForm("category")
	// 如果出现中文逗号，则替换为英文逗号
	tagIds = strings.ReplaceAll(tagIds, "，", ",")

	// 如果没有选择栏目，使用默认栏目
	if category == "" {
		category = conf.GetDefaultCategory()
	}

	// 分割关键词
	var keywordList []string
	if runtime.GOOS == "windows" {
		keywordList = strings.Split(keywords, "\r\n")
	} else {
		keywordList = strings.Split(keywords, "\n")
	}

	// 过滤空行
	var filteredKeywords []string
	for _, k := range keywordList {
		if k = strings.TrimSpace(k); k != "" {
			filteredKeywords = append(filteredKeywords, k)
		}
	}

	if len(filteredKeywords) == 0 {
		response.JSON(c, gin.H{
			"success": false,
			"message": "请输入至少一个关键词",
		})
		return
	}

	// 调用生成器
	gen := articlegenerate.NewArticleGenerator()

	successCount := 0
	var failedKeywords []string

	// 逐个处理关键词
	for _, keyword := range filteredKeywords {
		articles, err := gen.GenerateForKeyword(keyword, tagIds, count, isPublish)
		if err != nil {
			failedKeywords = append(failedKeywords, keyword)
			continue
		}

		// 保存生成的文章
		for _, result := range articles {
			_article := &article.Article{
				Title:    result.Title,
				Content:  result.Content,
				Keywords: result.Keywords,
				Status:   result.Status,
				TagIds:   result.TagIds,
				Category: category,
			}
			_article.Create()
		}
		successCount++
		// 每生成3条后停止2分钟
		if successCount%3 == 0 {
			time.Sleep(2 * time.Minute)
		}
		// 每生成10条后停止10分钟
		if successCount%10 == 0 {
			time.Sleep(5 * time.Minute)
		}
		// 等待10秒
		time.Sleep(10 * time.Second)
	}

	response.JSON(c, GenerateResult{
		Success:        successCount > 0,
		SuccessCount:   successCount,
		FailedCount:    len(failedKeywords),
		FailedKeywords: failedKeywords,
	})
}
